﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DCS.ComLib.Config;
using VietThuongLMS.Services;
using VietThuongLMS.ViewModels;
using VietThuongLMS.Utils;
using System.Web.Security;
using VietThuongLMS.Areas.Admin.Models;
using System.Text.RegularExpressions;
using System.IO;

namespace VietThuongLMS.Areas.Admin.Controllers
{
    public class GiaoVienController : Controller
    {
        //
        // GET: /Admin/GiaoVien/
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            int page = 1;
            if (Request["p"] != null)
            {
                page = int.Parse(Request["p"].ToString());
            }

            GiaoVienViewModel giaoVienList = GiaoVienService.GetGiaoVienList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page);

            //phân trang
            Pagination pagination = new Pagination(true, Url.Content("~"), "Admin", "GiaoVien", "Index", "?p=", giaoVienList.Total, page, int.Parse(ConfigReader.ReadString("ItemPerPage")), "Previous", "Next", "First", "End");
            string pageLinks = pagination.GetPageLinks();
            ViewData["pageLinks"] = pageLinks;
            //end phân trang

            return View(giaoVienList);
        }

        //
        // GET: /Admin/GiaoVien/Details/5
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        public ActionResult Detail(int id)
        {
            //GiaoVien gv = GiaoVienService.GetGiaoVienById(id);
            GiaoVienDetailViewModel viewModel = new GiaoVienDetailViewModel();
            viewModel.giaoVienModel = GiaoVienService.GetGiaoVienById(id);
            return View(viewModel);
        }

        //
        // GET: /Admin/GiaoVien/Create
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        public ActionResult Create()
        {
            using (LMSDataEntities context = new LMSDataEntities())
            {
                GiaoVien gv = new GiaoVien();
                List<object> values = new List<object>();
                values.Add(new { ID = "choose", Name = "--Giới Tính--" });
                values.AddRange(from GioiTinh gioiTinh in Enum.GetValues(typeof(GioiTinh))
                                select new { ID = gioiTinh, Name = gioiTinh.ToString() });

                ViewData["sexes"] = new SelectList(values, "Id", "Name");

                ViewData["LoaiMH"] = new SelectList((new MonHocService()).GetMonHocList(), "ID", "TenMonHoc");
                return View();
            }
        }

        //
        // POST: /Admin/GiaoVien/Create
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        [HttpPost, ValidateInput(false)]
        public ActionResult Create(FormCollection collection, HttpPostedFileBase templateFile)
        {
            GiaoVienModel model = new GiaoVienModel();
            if (ModelState.IsValid)
            {
                try
                {
                    // TODO: Add insert logic here
                    TaiKhoan tk = new TaiKhoan();

                    tk.MaTaiKhoan = collection["taiKhoan.UserName"].Trim();
                    //tk.MatKhau = FormsAuthentication.HashPasswordForStoringInConfigFile(collection["taiKhoan.Password"], "md5");
                    tk.MatKhau = FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "md5");
                    tk.HoTen = collection["taiKhoan.FullName"];
                    tk.DiaChi = collection["taiKhoan.Address"];
                    tk.DienThoai = collection["taiKhoan.Phone"];
                    tk.Email = collection["taiKhoan.Email"];
                    tk.Deleted = Utils.Constant.INACTIVE;
                    tk.MaLoaiTaiKhoan = Utils.Constant.ACCOUNT_ROLE_TEACHER;
                    tk.NgayDangKy = DateTime.Today;
                    tk.GioiTinh = collection["taiKhoan.Sex"];
                    tk.NgheNghiep = collection["taiKhoan.Job"];
                    tk.NoiCongTac = collection["taiKhoan.Location_Job"];
                    tk.Deleted = Utils.Constant.INACTIVE;
                    Converter c = new Converter();
                    tk.NgaySinh = c.StringToDate(collection["taiKhoan.Birthday"]);

                    model.taiKhoan = new AccountModel();
                    model.taiKhoan.FullName = tk.HoTen;

                    bool result = AccountService.InsertAccount(tk);
                    if (result)
                    {
                        GiaoVien gv = new GiaoVien();
                        gv.MaTaiKhoan = tk.ID;
                        //url
                        templateFile = Request.Files["Avatar"];
                        if (templateFile != null && !templateFile.FileName.Equals(""))
                        {
                            if (templateFile.ContentLength > 1048576)
                            {
                            }
                            else
                            {
                                string fileName = Path.GetFileName(templateFile.FileName);
                                DCS.ComLib.File.Log.Write("GiaoVienController::Create", "", this.Server.MapPath("~/Images/Avatar/"));
                                try
                                {
                                    fileName = Utils.Upload.UpdateImageWithSize(templateFile, 320, this.Server.MapPath("~/Images/Avatar/"));
                                }
                                catch (Exception ex)
                                {
                                    DCS.ComLib.File.Log.Write("GiaoVienController::Create", ex.StackTrace, ex.Message);
                                }
                                gv.Avatar = fileName;
                            }
                        }
                        ///

                        gv.Deleted = Utils.Constant.INACTIVE;
                        gv.HocVan = collection["HocVan"];
                        if (collection["KinhNghiemGiangDay"].ToString() != "")
                            gv.KinhNghiemGiangDay = int.Parse(collection["KinhNghiemGiangDay"].ToString());
                        else
                            gv.KinhNghiemGiangDay = 0;
                        gv.KinhNghiemBieuDien = collection["KinhNghiemBieuDien"];
                        gv.MaMonHoc = int.Parse(collection["ID"]);

                        bool r = GiaoVienService.InsertGiaoVien(gv);
                        if (r)
                            return RedirectToAction("Index", "GiaoVien", new { area = "Admin" });
                    }
                    return View("Create", model);
                }
                catch (Exception ex)
                {
                    DCS.ComLib.File.Log.Write("GiaoVienController::Create", ex.StackTrace, ex.Message);
                    return View("Create", model);
                }
            }
            //Invalid, redisplay form with errors
            return View("Create", model);
        }

        //
        // GET: /Admin/GiaoVien/Edit/5
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(int id)
        {
            GiaoVien gv = GiaoVienService.GetGiaoVienById(id);
            ViewData["LoaiMH"] = new SelectList((new MonHocService()).GetMonHocList(), "ID", "TenMonHoc");
            return View(gv);
        }

        //
        // POST: /Admin/GiaoVien/Edit/5
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection collection, HttpPostedFileBase templateFile)
        {
            GiaoVien gv = GiaoVienService.GetGiaoVienById(id);
            ViewData["LoaiMH"] = new SelectList((new MonHocService()).GetMonHocList(), "ID", "TenMonHoc");

            bool flag = true;
            if (collection["TaiKhoan.Email"].Length <= 0)
            {
                ModelState.AddModelError("TaiKhoan.Email", "(*) Email không được để trống");
                gv.TaiKhoanReference.Value.Email = collection["TaiKhoan.Email"];
                flag = false;
            }
            else
            {
                if (!Regex.IsMatch(collection["TaiKhoan.Email"], @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                {
                    gv.TaiKhoanReference.Value.Email = collection["TaiKhoan.Email"];
                    ModelState.AddModelError("TaiKhoan.Email", "(*) Email không hợp lệ");
                    flag = false;
                }
            }

            if (collection["TaiKhoan.HoTen"].Length <= 0)
            {
                ModelState.AddModelError("TaiKhoan.HoTen", "(*) Họ tên không được để trống");
                gv.TaiKhoanReference.Value.HoTen = collection["TaiKhoan.HoTen"];
                flag = false;
            }
            if (collection["TaiKhoan.DienThoai"].Length <= 0)
            {
                ModelState.AddModelError("TaiKhoan.DienThoai", "(*) Số điện thoại không được để trống");
                gv.TaiKhoanReference.Value.DienThoai = collection["TaiKhoan.DienThoai"];
                flag = false;
            }

            if (flag)
            {
                try
                {
                    // TODO: Add update logic here

                    TaiKhoan tk = new TaiKhoan();
                    tk.HoTen = collection["TaiKhoan.HoTen"];
                    tk.DiaChi = collection["TaiKhoan.DiaChi"];
                    tk.DienThoai = collection["TaiKhoan.DienThoai"];
                    tk.Email = collection["TaiKhoan.Email"];
                    tk.GioiTinh = collection["TaiKhoan.GioiTinh"];
                    Converter c = new Converter();
                    tk.NgaySinh = c.StringToDate(collection["taiKhoan.Birthday"]);
                    tk.ID = (int)gv.MaTaiKhoan;
                    //if (collection["TaiKhoan.MatKhau"] != null)
                    //    tk.MatKhau = FormsAuthentication.HashPasswordForStoringInConfigFile(collection["TaiKhoan.MatKhau"], "md5");

                    //tk.NgheNghiep = collection["TaiKhoan.Job"];
                    //tk.NoiCongTac = collection["TaiKhoan.Location_Job"];

                    //Ok
                    AccountService.Edit(tk);

                    //url
                    templateFile = Request.Files["Avatar"];
                    if (templateFile != null && !templateFile.FileName.Equals(""))
                    {
                        if (templateFile.ContentLength > 1048576)
                        {
                        }
                        else
                        {
                            string fileName = Path.GetFileName(templateFile.FileName);
                            DCS.ComLib.File.Log.Write("GiaoVienController::Create", "", this.Server.MapPath("~/Images/Avatar/"));
                            try
                            {
                                fileName = Utils.Upload.UpdateImageWithSize(templateFile, 320, this.Server.MapPath("~/Images/Avatar/"));
                            }
                            catch (Exception ex)
                            {
                                DCS.ComLib.File.Log.Write("GiaoVienController::Create", ex.StackTrace, ex.Message);
                            }
                            gv.Avatar = fileName;
                        }
                    }
                    ///

                    gv.HocVan = collection["HocVan"];
                    gv.KinhNghiemGiangDay = int.Parse(collection["KinhNghiemGiangDay"].ToString());
                    gv.KinhNghiemBieuDien = collection["KinhNghiemBieuDien"];
                    gv.MaMonHoc = int.Parse(collection["MaMonHoc"]);

                    //Ok
                    GiaoVienService.Edit(gv);

                    //return View(gv);
                    return RedirectToAction("Index", "GiaoVien", new { area = "Admin" });
                }
                catch (Exception ex)
                {
                    DCS.ComLib.File.Log.Write("GiaoVienController::Edit", ex.StackTrace, ex.Message);
                    return View();
                }
            }

            //Invalid, redisplay form with errors
            return View("Edit", gv);
        }

        //
        // GET: /Admin/GiaoVien/Delete/5
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Admin/GiaoVien/Delete/5
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        [HttpGet]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                //Get aacount id from Giaovien id
                //delete Giao vien id
                //delete account id
                GiaoVien gv = GiaoVienService.GetGiaoVienById(id);
                bool result = GiaoVienService.DeleteGiaoVien(id);
                if (result)
                {
                    TaiKhoan tk = AccountService.GetAccountById(gv.MaTaiKhoan.Value);
                    bool r = AccountService.DeleteAccount(tk.MaTaiKhoan);
                    if (r)
                    {
                        return RedirectToAction("Index", "GiaoVien", new { area = "Admin" });
                    }
                    else
                    {
                        return View();
                    }
                }
                else
                {
                    return View();
                }
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public bool CheckValid(string username)
        {
            if (AccountService.GetAccount(username) != null)
                return false;
            return true;
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Search()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult SearchResult(string s, string type)
        {
            LMSDataEntities context = new LMSDataEntities();

            var gv = new List<GiaoVien>();

            if (s != "")
            {
                switch (type)
                {
                    case "tendangnhap":
                        gv = context.GiaoViens.Where(a => a.TaiKhoan.MaTaiKhoan.Contains(s)).ToList();
                        break;
                    case "hoten":
                        gv = context.GiaoViens.Where(a => a.TaiKhoan.HoTen.Contains(s)).ToList();
                        break;
                    case "email":
                        gv = context.GiaoViens.Where(a => a.TaiKhoan.Email.Contains(s)).ToList();
                        break;
                    default:
                        gv = context.GiaoViens.Where(a => a.TaiKhoan.MaLoaiTaiKhoan == Constant.ACCOUNT_ROLE_TEACHER).ToList();
                        break;
                }
            }
            else
            {
                gv = context.GiaoViens.Where(a => a.TaiKhoan.MaLoaiTaiKhoan == Constant.ACCOUNT_ROLE_TEACHER).ToList();
            }

            //var gv = context.GiaoViens.Where(a => a.TaiKhoan.MaTaiKhoan.Contains(s) || a.TaiKhoan.Email.Contains(s) || a.TaiKhoan.DiaChi.Contains(s)
            //    || a.TaiKhoan.GioiTinh.Contains(s) || a.TaiKhoan.HoTen.Contains(s) || a.TaiKhoan.DiaChi.Contains(s)).ToList();

            GiaoVienViewModel gvm = new GiaoVienViewModel(gv, gv.Count());
            return PartialView(gvm);
        }

        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin")]
        public ActionResult ResetPass(int id)
        {
            return View();
        }

        //[Authorize]
        [Authorize(Roles = "Admin")]
        [HttpGet]
        public ActionResult ResetPass(string id)
        {
            try
            {
                GiaoVien gv = GiaoVienService.GetGiaoVienById(int.Parse(id));
                TaiKhoan data = new TaiKhoan();
                data.ID = int.Parse(gv.MaTaiKhoan.ToString());
                data.MatKhau = FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "md5");
                bool result = AccountService.ResetPass(data);
                if (result)
                {
                    return RedirectToAction("Index", "GiaoVien", new { area = "Admin" });
                }
                else
                {
                    return View();
                }
            }
            catch (Exception ex)
            {
                return View();
            }
        }
    }
}
